package com.image.util;

import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Date;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifDirectory;

/**
 * 图片处理类
 * @author 李江杰
 *
 */
/**
 * 图片处理类
 * @author 李江杰
 *
 */
public class ImageUtils {
		
		static Logger logger = Logger.getLogger(ImageUtils.class);
		
		//顺时针旋转90度（通过交换图像的整数像素RGB 值）  
	    public static BufferedImage rotateClockwise90(BufferedImage bi) {  
	        int width = bi.getWidth();  
	        int height = bi.getHeight();  
	        BufferedImage bufferedImage = new BufferedImage(height, width, bi.getType());  
	        for (int i = 0; i < width; i++)  
	            for (int j = 0; j < height; j++)  
	                bufferedImage.setRGB(height - 1 - j, width - 1 - i, bi.getRGB(i, j));  
	        return bufferedImage;  
	    }  
	    
	    //逆时针旋转90度（通过交换图像的整数像素RGB 值）  
	    public static BufferedImage rotateCounterclockwise90(BufferedImage bi) {  
	        int width = bi.getWidth();  
	        int height = bi.getHeight();  
	        BufferedImage bufferedImage = new BufferedImage(height, width, bi.getType());  
	        for (int i = 0; i < width; i++)  
	            for (int j = 0; j < height; j++)  
	                bufferedImage.setRGB(j, i, bi.getRGB(i, j));  
	        return bufferedImage;  
	    }  
      
    	//旋转180度（通过交换图像的整数像素RGB 值）  
        public static BufferedImage rotate180(BufferedImage bi) {  
            int width = bi.getWidth();  
            int height = bi.getHeight();  
            BufferedImage bufferedImage = new BufferedImage(width,height,bi.getType());  
            for (int i = 0; i < width; i++)  
                for (int j = 0; j < height; j++)  
                    bufferedImage.setRGB( width - i-1,height-j-1, bi.getRGB(i, j));  
            return bufferedImage;  
        }  
          
        //水平翻转  
        public static BufferedImage rotateHorizon(BufferedImage bi) {  
            int width = bi.getWidth();  
            int height = bi.getHeight();  
            BufferedImage bufferedImage = new BufferedImage(width,height,bi.getType());  
            for (int i = 0; i < width; i++)  
                for (int j = 0; j < height; j++)  
                    bufferedImage.setRGB( width - i-1,j, bi.getRGB(i, j));  
            return bufferedImage;  
        }  
        
        /** 
         * 图片翻转时，计算图片翻转到正常显示需旋转角度  
         * @throws Exception 
         */  
        @SuppressWarnings("deprecation")
        public static int getRotateAngleForPhoto(String rul,String fileName) throws Exception{  
            File file = new File(rul+ fileName);  
            int angel = 0;  
            Metadata metadata; 
            try{  
                metadata = JpegMetadataReader.readMetadata(file);  
                Directory directory = metadata.getDirectory(ExifDirectory.class);  
                if(directory.containsTag(ExifDirectory.TAG_ORIENTATION)){   
                    // Exif信息中方向　　  
                    int orientation = directory.getInt(ExifDirectory.TAG_ORIENTATION);
                    System.out.println("orientation---"+orientation);
                    // 原图片的方向信息  
                    if(6 == orientation ){  
                        //6顺时针90  
                        angel = 90;  
                        //图片压缩
            	        ImgCompress.setFile(rul+ fileName);			
            	        logger.info("开始：" + new Date().toLocaleString());  
            	        ImgCompress imgCom = new ImgCompress(rul+fileName);  
            	        imgCom.resizeFix(400, 400); 
            	        logger.info("结束：" + new Date().toLocaleString());  
                        File currentImg = new File(rul+ fileName);		//当前图片
            	        File rotateImg = new File(rul+ fileName);  		//旋转后保存图片
            	        BufferedImage image = ImageIO.read(currentImg);  
            	        //旋转
            	        image=ImageUtils.rotateCounterclockwise90(image);
            	        ImageIO.write(image, "png", rotateImg);
            	        //水平翻转  
            	        image=ImageUtils.rotateHorizon(image);
            	        ImageIO.write(image, "png", rotateImg);
                    }else if( 3 == orientation){  
                    	//3旋转180  
                        angel = 180;  
                        //图片压缩
            	        ImgCompress.setFile(rul+ fileName);			
            	        logger.info("开始：" + new Date().toLocaleString());  
            	        ImgCompress imgCom = new ImgCompress(rul+fileName);  
            	        imgCom.resizeFix(400, 400); 
            	        logger.info("结束：" + new Date().toLocaleString()); 
                        File currentImg = new File(rul+ fileName);	//当前图片
            	        File rotateImg = new File(rul+ fileName);  	//旋转后保存图片
            	        BufferedImage image = ImageIO.read(currentImg);  
            	        //旋转
            	        image=ImageUtils.rotate180(image);
            	        ImageIO.write(image, "png", rotateImg);
                    }else if( 8 == orientation){  
                    	//逆时针90
                        angel = 270;  
                        //图片压缩
            	        ImgCompress.setFile(rul+ fileName);			
            	        logger.info("开始：" + new Date().toLocaleString());  
            	        ImgCompress imgCom = new ImgCompress(rul+fileName);  
            	        imgCom.resizeFix(400, 400); 
            	        logger.info("结束：" + new Date().toLocaleString());
                        File currentImg = new File(rul+ fileName);	//当前图片
            	        File rotateImg = new File(rul+ fileName);  	//旋转后保存图片
            	        BufferedImage image = ImageIO.read(currentImg);  
            	        //旋转
            	        image=ImageUtils.rotateClockwise90(image);
            	        ImageIO.write(image, "png", rotateImg);
            	        //水平翻转  
            	        image=ImageUtils.rotateHorizon(image);
            	        ImageIO.write(image, "png", rotateImg);
                    }
                }  
            } catch(JpegProcessingException e){  
                e.printStackTrace();  
            } catch(MetadataException e){  
                e.printStackTrace();  
            }  
            logger.info("图片旋转角度：" + angel);  
            return angel;  
        }  
        /** 
        * 计算旋转参数 
        */  
        public static Rectangle CalcRotatedSize(Rectangle src,int angel){  
            // if angel is greater than 90 degree,we need to do some conversion.  
            if(angel > 90){  
                if(angel / 9%2 ==1){  
                    int temp = src.height;  
                    src.height = src.width;  
                    src.width = temp;  
                }  
                angel = angel % 90;  
            }  
            double r = Math.sqrt(src.height * src.height + src.width * src.width ) / 2 ;  
            double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;  
            double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;    
            double angel_dalta_width = Math.atan((double) src.height / src.width);    
            double angel_dalta_height = Math.atan((double) src.width / src.height);    
            int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha    
                    - angel_dalta_width));    
            int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha    
                    - angel_dalta_height));    
            int des_width = src.width + len_dalta_width * 2;    
            int des_height = src.height + len_dalta_height * 2;    
            return new java.awt.Rectangle(new Dimension(des_width, des_height));    
        }  
}
